let userBalance = 100;
let selectedRed = [];
let selectedBlue = null;
let currentBet = null;
let betHistory = [];
let continuousDrawCount = 0;

// 添加彩种配置
const LOTTERY_TYPES = {
  SSQ: {
    name: '双色球',
    code: 'SSQ',
    drawInterval: 259200000, // 3天开奖一次
    redBalls: { count: 6, max: 33 },
    blueBalls: { count: 1, max: 16 },
    price: 2,
    rules: [
      { level: "一等奖", condition: "6红+1蓝", prize: 5000000 },
      { level: "二等奖", condition: "6红+0蓝", prize: 1000000 },
      { level: "三等奖", condition: "5红+1蓝", prize: 3000 },
      { level: "四等奖", condition: "5红+0蓝或4红+1蓝", prize: 200 },
      { level: "五等奖", condition: "4红+0蓝或3红+1蓝", prize: 10 },
      { level: "六等奖", condition: "1蓝", prize: 5 }
    ]
  },
  QLC: {
    name: '七乐彩',
    code: 'QLC',
    drawInterval: 259200000,
    redBalls: { count: 7, max: 30 },
    blueBalls: { count: 0, max: 0 },
    price: 2,
    rules: [
      { level: "一等奖", condition: "7个号全中", prize: 1000000 },
      { level: "二等奖", condition: "6个号", prize: 50000 },
      { level: "三等奖", condition: "5个号", prize: 1000 }
    ]
  },
  FAST3: {
    name: '快3',
    code: 'FAST3',
    drawInterval: 60000, // 1分钟开奖
    dice: { count: 3, max: 6 },
    price: 2,
    rules: [
      { level: "和值", condition: "3个骰子点数和", prize: "根据和值不同" },
      { level: "三同号", condition: "三个相同号码", prize: 240 },
      { level: "二同号", condition: "两个相同号码", prize: 80 }
    ]
  },
  PK10: {
    name: '北京PK10',
    code: 'PK10',
    drawInterval: 60000,
    numbers: { count: 2, max: 10 }, // 选择冠亚军
    price: 2,
    rules: [
      { level: "冠军", condition: "第一名", prize: 18 },
      { level: "冠亚和", condition: "冠亚军和值", prize: "根据和值不同" }
    ]
  }
};

// 当前选择的彩种
let currentLottery = LOTTERY_TYPES.SSQ;

// 添加用户信息相关的全局变量
let userInfo = {
  nickname: '未设置昵称',
  avatar: null,
  totalBets: 0,
  totalWins: 0,
  transactions: []
};

// 在HTML文件末尾添加这个脚本
document.addEventListener('DOMContentLoaded', function () {
  // 生成红球
  const redBallsContainer = document.getElementById('redBalls');
  for (let i = 1; i <= 33; i++) {
    const ball = document.createElement('div');
    ball.className = 'ball red-ball';
    ball.textContent = i;
    ball.onclick = () => selectRedBall(i, ball);
    redBallsContainer.appendChild(ball);
  }

  // 生成蓝球
  const blueBallsContainer = document.getElementById('blueBalls');
  for (let i = 1; i <= 16; i++) {
    const ball = document.createElement('div');
    ball.className = 'ball blue-ball';
    ball.textContent = i;
    ball.onclick = () => selectBlueBall(i, ball);
    blueBallsContainer.appendChild(ball);
  }

  updateBalance();

  // 初始化奖级表格
  initPrizeTable();

  // 从localStorage加载投注历史
  loadHistory();

  // 加载保存的主题
  const savedTheme = localStorage.getItem('theme');
  if (savedTheme === 'dark') {
    document.body.setAttribute('data-theme', 'dark');
    document.getElementById('themeToggle').innerHTML = '🌙 Dark Mode';
  }

  // 投注按钮添加动画延迟
  document.querySelectorAll('.betting-options button').forEach((btn, index) => {
    btn.style.setProperty('--btn-index', index);
  });

  // 加载用户信息
  loadUserInfo();
  updateUserStats();

  // 移动端检测
  if (isMobile()) {
    initMobileFeatures();
  }

  initLotteryTabs();
  startCountdown();
});

function selectRedBall(number, element) {
  if (selectedRed.includes(number)) {
    selectedRed = selectedRed.filter(n => n !== number);
    element.classList.remove('selected');
    element.removeAttribute('data-index');
    updateRedBallIndexes();
  } else if (selectedRed.length < 6) {
    selectedRed.push(number);
    element.classList.add('selected');
    updateRedBallIndexes();
  }
}

function selectBlueBall(number, element) {
  const blueBalls = document.querySelectorAll('.blue-ball');
  blueBalls.forEach(ball => {
    ball.classList.remove('selected');
    ball.removeAttribute('data-index');
  });

  if (selectedBlue === number) {
    selectedBlue = null;
  } else {
    selectedBlue = number;
    element.classList.add('selected');
    element.setAttribute('data-index', '1');
  }
}

function updateRedBallIndexes() {
  document.querySelectorAll('.red-ball').forEach(ball => {
    const number = parseInt(ball.textContent);
    const index = selectedRed.indexOf(number);
    if (index !== -1) {
      ball.setAttribute('data-index', index + 1);
    } else {
      ball.removeAttribute('data-index');
    }
  });
}

function placeBet() {
  if (selectedRed.length !== 6 || selectedBlue === null) {
    alert('请选择6个红球和1个蓝球');
    return;
  }

  const multiple = parseInt(document.getElementById('multipleInput').value) || 1;
  const totalCost = 2 * multiple;

  if (userBalance < totalCost) {
    alert('余额不足');
    return;
  }

  userBalance -= totalCost;
  const bet = {
    id: Date.now(),
    red: [...selectedRed].sort((a, b) => a - b),
    blue: selectedBlue,
    multiple: multiple,
    time: new Date().toLocaleString(),
    status: '待开奖',
    prize: 0
  };

  if (document.getElementById('continuousDraw').checked) {
    continuousDrawCount = 5;
  }

  betHistory.unshift(bet);
  saveHistory();
  updateHistoryDisplay();
  updateBalance();
  addTransaction('投注', -totalCost);

  showNotification(`成功投注 ${multiple} 倍`);
}

function drawLottery() {
  if (!currentBet) {
    alert('请先投注');
    return;
  }

  let winningNumbers;
  switch (currentLottery.code) {
    case 'SSQ':
      winningNumbers = {
        red: generateRandomNumbers(6, 33),
        blue: Math.floor(Math.random() * 16) + 1
      };
      break;

    case 'QLC':
      winningNumbers = {
        red: generateRandomNumbers(7, 30)
      };
      break;

    case 'FAST3':
      winningNumbers = {
        dice: Array(3).fill(0).map(() => Math.floor(Math.random() * 6) + 1)
      };
      break;

    case 'PK10':
      winningNumbers = {
        numbers: generateRandomNumbers(10, 10)
      };
      break;
  }

  // 计算中奖情况并更新界面
  calculatePrize(winningNumbers);
}

function generateRandomNumbers(count, max) {
  const numbers = [];
  while (numbers.length < count) {
    const num = Math.floor(Math.random() * max) + 1;
    if (!numbers.includes(num)) {
      numbers.push(num);
    }
  }
  return numbers.sort((a, b) => a - b);
}

function calculatePrize(redMatches, blueMatch) {
  if (redMatches === 6 && blueMatch) return 5000000; // 一等奖
  if (redMatches === 6) return 1000000; // 二等奖
  if (redMatches === 5 && blueMatch) return 3000;
  if (redMatches === 5 || (redMatches === 4 && blueMatch)) return 200;
  if (redMatches === 4 || (redMatches === 3 && blueMatch)) return 10;
  if (blueMatch) return 5;
  return 0;
}

function addBalance() {
  const amount = parseInt(prompt('请输入充值金额：'));
  if (!isNaN(amount) && amount > 0) {
    userBalance += amount;
    addTransaction('充值', amount);
    updateBalance();
  }
}

function updateBalance() {
  document.getElementById('userBalance').textContent = userBalance;
}

function resetSelection() {
  selectedRed = [];
  selectedBlue = null;
  document.querySelectorAll('.ball').forEach(ball => ball.classList.remove('selected'));
}

function randomSelect() {
  resetSelection();
  selectedRed = generateRandomNumbers(6, 33);
  selectedBlue = Math.floor(Math.random() * 16) + 1;

  // 更新UI显示
  document.querySelectorAll('.red-ball').forEach(ball => {
    const number = parseInt(ball.textContent);
    if (selectedRed.includes(number)) {
      ball.classList.add('selected');
    }
  });
  updateRedBallIndexes();

  document.querySelectorAll('.blue-ball').forEach(ball => {
    const number = parseInt(ball.textContent);
    if (number === selectedBlue) {
      ball.classList.add('selected');
      ball.setAttribute('data-index', '1');
    }
  });

  showNotification('已为您机选号码');
}

function clearSelection() {
  resetSelection();
  showNotification('已清空选择');
}

function updateHistoryDisplay() {
  const historyList = document.getElementById('historyList');
  historyList.innerHTML = betHistory.map((bet, index) => `
    <div class="history-item ${bet.prize > 0 ? 'won glow' : ''}" 
         style="animation-delay: ${index * 0.1}s">
      <p>投注时间: ${bet.time}</p>
      <p>红球: ${bet.red.join(', ')} | 蓝球: ${bet.blue}</p>
      <p>倍数: ${bet.multiple}倍 | 状态: ${bet.status}</p>
      ${bet.matchResult ? `
        <p>开奖号码: ${bet.matchResult.winningRed.join(', ')} | ${bet.matchResult.winningBlue}</p>
        <p>中奖情况: 红球${bet.matchResult.redMatches}个 | 蓝球${bet.matchResult.blueMatch ? '√' : '×'}</p>
      ` : ''}
      <p>奖金: ¥${bet.prize}</p>
    </div>
  `).join('');
}

function showNotification(message) {
  const notification = document.createElement('div');
  notification.className = 'notification glow';
  notification.innerHTML = `
    <span style="transform: translateZ(10px);">${message}</span>
  `;
  document.body.appendChild(notification);

  if (isMobile()) {
    notification.style.transform = 'translateY(20px)';
    setTimeout(() => {
      notification.style.transform = 'translateY(0)';
      notification.style.opacity = '0';
      notification.style.transition = 'all 0.3s ease';
      setTimeout(() => notification.remove(), 300);
    }, 2000);
  } else {
    // 添加3D动画效果
    notification.style.transform = 'translateZ(50px) rotateX(10deg)';

    setTimeout(() => {
      notification.style.opacity = '0';
      notification.style.transform = 'translateZ(-50px) rotateX(-10deg)';
      notification.style.transition = 'all 0.5s ease';

      setTimeout(() => notification.remove(), 500);
    }, 2000);
  }
}

function saveHistory() {
  localStorage.setItem('betHistory', JSON.stringify(betHistory));
}

function loadHistory() {
  const saved = localStorage.getItem('betHistory');
  if (saved) {
    betHistory = JSON.parse(saved);
    updateHistoryDisplay();
  }
}

function initPrizeTable() {
  const table = document.getElementById('prizeTable');
  currentLottery.rules.forEach(rule => {
    const row = table.insertRow();
    row.insertCell().textContent = rule.level;
    row.insertCell().textContent = rule.condition;
    row.insertCell().textContent = `¥${rule.prize.toLocaleString()}`;
  });
}

// 添加主题切换功能
function toggleTheme() {
  const body = document.body;
  const button = document.getElementById('themeToggle');
  const currentTheme = body.getAttribute('data-theme');

  if (currentTheme === 'dark') {
    body.removeAttribute('data-theme');
    button.innerHTML = '🌞 Light Mode';
    localStorage.setItem('theme', 'light');
  } else {
    body.setAttribute('data-theme', 'dark');
    button.innerHTML = '🌙 Dark Mode';
    localStorage.setItem('theme', 'dark');
  }
}

// 用户信息相关函数
function loadUserInfo() {
  const savedInfo = localStorage.getItem('userInfo');
  if (savedInfo) {
    userInfo = JSON.parse(savedInfo);
    updateUserInfoDisplay();
  }
}

function saveUserInfo() {
  localStorage.setItem('userInfo', JSON.stringify(userInfo));
}

function updateUserInfoDisplay() {
  document.getElementById('userNickname').textContent = userInfo.nickname;
  if (userInfo.avatar) {
    document.getElementById('userAvatar').querySelector('img').src = userInfo.avatar;
    document.getElementById('profileAvatar').src = userInfo.avatar;
  }
  document.getElementById('nicknameInput').value = userInfo.nickname;
  updateUserStats();
}

function handleAvatarChange(event) {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = function (e) {
      userInfo.avatar = e.target.result;
      updateUserInfoDisplay();
      saveUserInfo();
    };
    reader.readAsDataURL(file);
  }
}

function updateUserStats() {
  document.getElementById('totalBets').textContent = `¥${userInfo.totalBets.toLocaleString()}`;
  document.getElementById('totalWins').textContent = `¥${userInfo.totalWins.toLocaleString()}`;
  document.getElementById('netProfit').textContent = `¥${(userInfo.totalWins - userInfo.totalBets).toLocaleString()}`;
  updateTransactionList();
}

function updateTransactionList() {
  const list = document.getElementById('transactionList');
  list.innerHTML = userInfo.transactions.map(transaction => `
    <div class="transaction-item">
      <div class="transaction-info">
        <div class="transaction-type">${transaction.type}</div>
        <div class="transaction-time">${transaction.time}</div>
      </div>
      <div class="amount ${transaction.amount > 0 ? 'positive' : 'negative'}">
        ${transaction.amount > 0 ? '+' : ''}¥${transaction.amount.toLocaleString()}
      </div>
    </div>
  `).join('');
}

function addTransaction(type, amount) {
  const transaction = {
    type,
    amount,
    time: new Date().toLocaleString()
  };
  userInfo.transactions.unshift(transaction);
  if (amount > 0) {
    userInfo.totalWins += amount;
  } else {
    userInfo.totalBets += Math.abs(amount);
  }
  saveUserInfo();
  updateUserStats();
}

// 面板控制函
function openUserPanel() {
  document.getElementById('userPanel').classList.add('active');
}

function closeUserPanel() {
  document.getElementById('userPanel').classList.remove('active');
}

function saveUserInfo() {
  const nickname = document.getElementById('nicknameInput').value.trim();
  if (nickname) {
    userInfo.nickname = nickname;
    saveUserInfo();
    updateUserInfoDisplay();
    showNotification('保存成功');
  }
}

// 移动端功能初始化
function initMobileFeatures() {
  // 添加触摸反馈
  document.querySelectorAll('button, .ball').forEach(element => {
    element.addEventListener('touchstart', function () {
      this.style.opacity = '0.7';
    });

    element.addEventListener('touchend', function () {
      this.style.opacity = '1';
    });
  });

  // 处理软键盘弹出时的布局问题
  const inputs = document.querySelectorAll('input[type="text"], input[type="number"]');
  inputs.forEach(input => {
    input.addEventListener('focus', () => {
      document.body.scrollTop = input.offsetTop - 10;
    });
  });

  // 添加下拉刷新功能
  let touchStartY = 0;
  document.addEventListener('touchstart', e => {
    touchStartY = e.touches[0].clientY;
  }, { passive: true });

  document.addEventListener('touchmove', e => {
    const touchY = e.touches[0].clientY;
    const scrollTop = document.documentElement.scrollTop;

    if (scrollTop === 0 && touchY - touchStartY > 50) {
      showPullToRefreshHint();
    }
  }, { passive: true });

  document.addEventListener('touchend', e => {
    const touchY = e.changedTouches[0].clientY;
    const scrollTop = document.documentElement.scrollTop;

    if (scrollTop === 0 && touchY - touchStartY > 100) {
      refreshData();
    }
    hidePullToRefreshHint();
  }, { passive: true });
}

// 检测是否为移动设备
function isMobile() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

// 显示下拉刷新提示
function showPullToRefreshHint() {
  let hint = document.querySelector('.pull-to-refresh');
  if (!hint) {
    hint = document.createElement('div');
    hint.className = 'pull-to-refresh';
    hint.textContent = '下拉刷新';
    document.body.insertBefore(hint, document.body.firstChild);
  }
}

// 隐藏下拉刷新提示
function hidePullToRefreshHint() {
  const hint = document.querySelector('.pull-to-refresh');
  if (hint) {
    hint.remove();
  }
}

// 刷新数据
function refreshData() {
  loadHistory();
  loadUserInfo();
  showNotification('刷新成功');
}

// 添加彩种切换功能
function initLotteryTabs() {
  document.querySelectorAll('.lottery-tab').forEach(tab => {
    tab.addEventListener('click', () => {
      const type = tab.dataset.type;
      switchLotteryType(type);
    });
  });
}

function switchLotteryType(type) {
  currentLottery = LOTTERY_TYPES[type];
  document.querySelectorAll('.lottery-tab').forEach(tab => {
    tab.classList.toggle('active', tab.dataset.type === type);
  });

  resetSelection();
  updateLotteryUI();
  startCountdown();
}

function updateLotteryUI() {
  const numberSelect = document.querySelector('.number-select');

  switch (currentLottery.code) {
    case 'SSQ':
    case 'QLC':
      numberSelect.innerHTML = `
        <h3>选择${currentLottery.code === 'SSQ' ? '红球' : '号码'}（选${currentLottery.redBalls.count}个）</h3>
        <div id="redBalls"></div>
        ${currentLottery.code === 'SSQ' ? `
          <h3>选择蓝球（选1个）</h3>
          <div id="blueBalls"></div>
        ` : ''}
      `;
      generateBalls();
      break;

    case 'FAST3':
      numberSelect.innerHTML = `
        <h3>选择玩法</h3>
        <div class="betting-types">
          <button onclick="selectBettingType('sum')">和值</button>
          <button onclick="selectBettingType('triple')">三同号</button>
          <button onclick="selectBettingType('double')">二同号</button>
        </div>
        <div class="dice-container">
          <div class="dice" id="dice1"></div>
          <div class="dice" id="dice2"></div>
          <div class="dice" id="dice3"></div>
        </div>
      `;
      break;

    case 'PK10':
      numberSelect.innerHTML = `
        <h3>选择冠亚军</h3>
        <div class="pk10-numbers" id="pk10Numbers"></div>
      `;
      generatePK10Numbers();
      break;
  }
}

function generateBalls() {
  const { redBalls, blueBalls } = currentLottery;

  if (redBalls.count > 0) {
    const redContainer = document.getElementById('redBalls');
    redContainer.innerHTML = '';
    for (let i = 1; i <= redBalls.max; i++) {
      const ball = document.createElement('div');
      ball.className = 'ball red-ball';
      ball.textContent = i;
      ball.onclick = () => selectRedBall(i, ball);
      redContainer.appendChild(ball);
    }
  }

  if (blueBalls?.count > 0) {
    const blueContainer = document.getElementById('blueBalls');
    blueContainer.innerHTML = '';
    for (let i = 1; i <= blueBalls.max; i++) {
      const ball = document.createElement('div');
      ball.className = 'ball blue-ball';
      ball.textContent = i;
      ball.onclick = () => selectBlueBall(i, ball);
      blueContainer.appendChild(ball);
    }
  }
}

function startCountdown() {
  const countdownElement = document.getElementById('countdown');
  let nextDraw = Date.now() + currentLottery.drawInterval;

  function updateCountdown() {
    const now = Date.now();
    const diff = nextDraw - now;

    if (diff <= 0) {
      nextDraw = now + currentLottery.drawInterval;
      if (currentBet) {
        drawLottery();
      }
    }

    const hours = Math.floor(diff / 3600000);
    const minutes = Math.floor((diff % 3600000) / 60000);
    const seconds = Math.floor((diff % 60000) / 1000);

    countdownElement.textContent =
      `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  }

  updateCountdown();
  setInterval(updateCountdown, 1000);
} 